/*
 * FlightGenerator.cpp
 *
 *  Created on: Sep 10, 2013
 *      Author: gonprieto
 */

#include "FlightGenerator.h"
#include "utils/Logger.h"
#include "entities/Flight.h"
#include "utils/SimulatorUtils.h"


FlightGenerator::FlightGenerator(unsigned int cantidadVuelos):towerControlInboxBox(SimulatorUtils::getTowerInboxName()) {
	this->cantidadVuelos = cantidadVuelos;
	this->log = Logger::instancia();
	this->esPadre = true;
}

int FlightGenerator::startNewFlight(int flightId) {
	pid_t pid;

	switch (pid = fork()) {
	case -1:
		return -1;
	case 0: {
		log << "FlightGenerator::startNewFlight - Creo nuevo flightId: "<< flightId << eol;
		esPadre = false;

		int opcion = rand() % 2;

		Status choosed = IN_THE_AIR;
		if(opcion == 1){
			choosed = PARKED;
			Logger::instancia() << "FlightGenerator::startNewFlight - spawning flight con estado PARKED" << eol ;
		}else{
			Logger::instancia() << "FlightGenerator::startNewFlight - spawning flight con estado IN_THE_AIR" << eol ;
		}

		log << "FlightGenerator::startNewFlight - Flight creado y corriendo flightId:" << flightId << eol;
		Flight f(flightId,choosed);
		f.run();

		return 0;
	}
	default: {
		log << "TowerControl::startNewController - Agrego el controller id a la lista pid : " << pid << eol;
		this->flightsIds.push_back(pid);
		return pid;
	}
	}
}


int FlightGenerator::run(){
	//Espero q inicie todo

	for (unsigned int i = 0; i < this->cantidadVuelos; i++){
		if (startNewFlight(i) == 0){
			return 0;
		}
	}

	if(esPadre){
		log << "FlightGenerator::run - Esperando que los flight terminen su proceso" << eol;
		waitAllFlight();

		log << "FlightGenerator::run - Fin FlightGenerator. Envio mensaje a controller" << eol ;
		this->towerControlInboxBox.endFlightGenerator();
		this->towerControlInboxBox.cerrar();
	}

	return 0;
}

void FlightGenerator::waitAllFlight() {
	int status;
	std::vector<pid_t>::iterator pids;

	for (pids = this->flightsIds.begin();pids != this->flightsIds.end(); pids++) {
		waitpid((*pids), &status, 0);
	}

	this->flightsIds.clear();
}

FlightGenerator::~FlightGenerator() {

}


